package com.zhangzhan.filter;

import com.alibaba.fastjson.JSON;
import com.zhangzhan.domain.commcon.ResponseResult;
import com.zhangzhan.domain.entity.LoginUser;
import com.zhangzhan.domain.enums.AppHttpCodeEnum;
import com.zhangzhan.utils.JwtUtil;
import com.zhangzhan.utils.RedisCache;
import com.zhangzhan.utils.WebUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 张一恒
 * @version 1.0
 */
//token权限认证过滤器
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;

    //重写过滤器方法
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //根据前端的对接，从请求头中获取token
        String token = request.getHeader("token");
        //这里还要判断一下token是否有值
        if(!Strings.hasText(token)){
            //没有则放行 后面还是要被拦截
            filterChain.doFilter(request,response);
            return;
        }
        //然后解析出token 获取userid
        Claims claims = null;
        try {
             claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //判断 如果token超时了或者非法token需要响应到前端一个状态码其重新登录
            ResponseResult result =  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //获取解析后的数据
        String userId = claims.getSubject();
        //然后从redis中根据id获取user
        LoginUser loginUser = redisCache.getCacheObject("login:"+userId);
        //判断loginUser是否有数据
        if (Objects.isNull(loginUser)){
            //判断 如果参数伪造或为空需要响应到前端一个状态码其重新登录
            ResponseResult result =  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //存到securitycontextHolde中
        //使用实现子类封装到SecurityContextHolder参数中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //最后放行
        filterChain.doFilter(request,response);
    }
}
